﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web;

namespace Shsc.Net.FrameWork.Common.Util
{
    /// <summary>
    /// 对象拷贝
    /// </summary>
    public class ConvertUtil
    {
        /// <summary>
        /// 对象拷贝
        /// </summary>
        /// <param name="orig">源</param>
        /// <param name="dest">目的</param>
        public static void CopyProperties(object orig, object dest)
        {
            if (orig == null || dest == null)
            {
                return;
            }
            PropertyInfo[] souceProperties = orig.GetType().GetProperties();
            foreach (PropertyInfo pInfo in souceProperties)
            {
                PropertyInfo descInfo = dest.GetType().GetProperty(pInfo.Name);
                if (descInfo != null
                    && descInfo.CanWrite
                    && descInfo.PropertyType.Name == pInfo.PropertyType.Name)
                {
                    descInfo.SetValue(dest, pInfo.GetValue(orig, null), null);
                }
            }
        }

        /// <summary>
        /// 对象拷贝（按字段）
        /// </summary>
        /// <param name="orig"></param>
        /// <param name="dest"></param>
        /// <param name="propertyNames"></param>
        public static void CopyProperties(object orig, object dest, params string[] propertyNames)
        {
            if (orig == null || dest == null)
            {
                return;
            }
            foreach (string pName in propertyNames)
            {
                PropertyInfo pInfo = orig.GetType().GetProperty(pName);
                if (pInfo == null) continue;
                PropertyInfo descInfo = dest.GetType().GetProperty(pInfo.Name);
                if (descInfo != null
                    && descInfo.CanWrite
                    && descInfo.PropertyType.Name == pInfo.PropertyType.Name)
                {
                    descInfo.SetValue(dest, pInfo.GetValue(orig, null), null);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="destDto"></param>
        public static void GetPageData(object destDto)
        {
            PropertyInfo[] PropertyInfos = destDto.GetType().GetProperties();
            foreach (PropertyInfo info in PropertyInfos)
            {
                if (!string.IsNullOrEmpty(HttpContext.Current.Request[info.Name]))
                {
                    info.SetValue(destDto, HttpContext.Current.Request[info.Name], null);
                }
            }
        }
    }
}
